import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router-dom'
import css from './postMsg.module.scss'
class SpacePostMsg extends PureComponent {
    contentRef = React.createRef()

    static propTypes = {
        id: PropTypes.oneOfType([
            PropTypes.number,
            PropTypes.string
        ]),
        msg: PropTypes.string,
        /* 
            at召唤人的格式
            [
                {
                data: 用户id,
                length: 用户名长度,
                location: 用户名位置,
                type: 1 用户: 1 | 抽奖：2 | 投票：3
                }
            ]
        */
        ats: PropTypes.array,
        /*
            emoji图片格式
            [
                {
                emoji_name: [tv_腼腆],
                text: [tv_腼腆],
                url: '图片地址'
                }
            ]
        */
        emojis: PropTypes.array,
        /*
            // 话题数组格式
            [
                {
                is_activity: 1
                topic_id: 7085462
                topic_link: ""
                topic_name: "阅片无数"
                }
            ]
        */   
        topics: PropTypes.array,
        /*
            // 投票格式
            {
                desc: "投票标题"
                join_num: 参与人数
                vote_id: 投票id
            }
        */
        votes: PropTypes.object
    }

    state = {
        expand: false,
        enableExpand: false
    }

    get urlReg() {
        return /(https?:\/\/(\w+\.)?(bilibili|biligame|acg|b23)\.(com|tv)[/.$*?~=#!%@&\-\w]*)/g
    }
    get btnText () {
        return this.state.expand ? '收起' : '展开'
    }

    get formatMsg() {
        let tempMsg = this.props.msg
        const { ats, topics, emojis, votes } = this.props
        // 替换用户|抽奖
        if (ats.length) {
          const users = []
          // 先获取到用户名称
          for (const at of ats) {
            const { data, location, length, type } = at
            let str = ''
            if (type === 1) {
              str = tempMsg.substr(location, length)
            } else if (type === 2 || type === 4) {
              str = tempMsg.substring(location, location + (data - 0))
            }
            users.push({
              name: str,
              id: data,
              type
            })
          }
          let lastUserName = null
          for (const user of users) {
            const { name, id, type } = user
            const userReg = new RegExp(name, 'gm')
            if (type === 1) {
              tempMsg = tempMsg.replace(userReg, `<span class="highlight" data-url="/space/${id}">${name}</span>`)
            } else if (type === 2) {
              tempMsg = tempMsg.replace(userReg, `<span class="highlight lottery" data-url="/lottery/${this.props.id}">${name}</span>`)
            } else if (type === 4) {
              if (lastUserName !== name) {
                tempMsg = tempMsg.replace(userReg, `<span class="highlight">${name}</span>`)
              }
            }
            lastUserName = name
          }
        }
        // 替换话题
        if (topics.length) {
          for (const topic of topics) {
            const name = topic.topic_name
            const tag = `#${name}#`
            const reg = new RegExp(tag, 'gm')
            tempMsg = tempMsg.replace(reg, `<span class="highlight" data-url="/topic/${name}">${tag}</span>`)
          }
        }
  
        // 替换投票
        if (votes) {
          const { desc, vote_id } = votes
          const voteReg = new RegExp(desc, 'gm')
          tempMsg = tempMsg.replace(voteReg, `<span class="highlight vote" data-url="/vote/${vote_id}">${desc}</span>`)
        }
  
        // 替换表情
        if (emojis.length) {
          for (const emoji of emojis) {
            const emojiName = emoji.emoji_name
            const emojiUrl = emoji.url
            const emojiTag = emojiName.replace('[', '\\[').replace(/_/g, '\\_').replace(']', '\\]')
            const emojiReg = new RegExp(emojiTag, 'gm')
            tempMsg = tempMsg.replace(emojiReg, `<img src="${emojiUrl}" style="vertical-align:middle" width="22" height="22" alt="${emojiName}" />`)
          }
        }
        tempMsg = tempMsg.replace(/\n/g, '<br>')
        // 替换网址
        tempMsg = tempMsg.replace(this.urlReg, '<a class="url" href="$1" target="_blank">网页链接</a>')
        return tempMsg
    }

    toggle = () => {
        this.setState({
            expand: !this.state.expand
        })
    }
    redirect = (e) => {
        const target = e.target
        const tag = target.tagName.toLowerCase()
        if (tag === 'span') {
          const { url } = target.dataset
          url && this.props.history.push(url)
        }
    }

    componentDidMount() {
        this.setState({
            enableExpand: this.contentRef.current.scrollHeight > this.contentRef.current.clientHeight
        })        
    }

    render() {
        const { expand, enableExpand } = this.state
        return (
            <div className={css["msg"]}>
                <div className={css["content"]}>
                    <div ref={this.contentRef} className={css[expand ? 'text-expand': 'text']} dangerouslySetInnerHTML={{__html: this.formatMsg}} onClick={this.redirect}></div>
                    { enableExpand && <div className={css["btn"]} onClick={this.toggle}>{ this.btnText }</div> }
                </div>
            </div>
        )
    }
}

export default withRouter(SpacePostMsg)